package org.jmat.batch.tasklet;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;



public class CleanTasklet implements Tasklet, InitializingBean {
	
	private final Log log = LogFactory.getLog(CleanTasklet.class);
	private Resource directoryFiles;	
	
	public Resource getDirectoryFiles() {
		return directoryFiles;
	}

	public void setDirectoryFiles(Resource directoryFiles) {
		this.directoryFiles = directoryFiles;
	}

	public CleanTasklet() {
		super();
	}

	@SuppressWarnings("unchecked")
	public ExitStatus execute() throws Exception {
		
		File rootFile  = directoryFiles.getFile();
		Assert.state(rootFile.isDirectory(),"rootFile : " + rootFile.getAbsolutePath());
		if (log.isDebugEnabled()){
			log.debug("directory = " + rootFile.getAbsolutePath());
		}
		
		// Get list of files in the directory
		Collection<File> listFiles = new HashSet<File>();
		listFiles = getListOfFiles(rootFile.getAbsolutePath(), "*.txt");
		
		boolean deleteStatus = false;
		for (File currentFile : listFiles){
			deleteStatus = currentFile.delete();
			if (log.isDebugEnabled()){
				if (deleteStatus) {
					log.debug("Delete " + currentFile.getName() + "with success.");
				}
				else {
					log.debug("Delete " + currentFile.getName() + "with error.");
				}
			}
		}

		
		return ExitStatus.FINISHED;
	}
	
	public void afterPropertiesSet() throws Exception {
		 Assert.notNull(directoryFiles,"directoryFiles must be set");
	}
	
	/**
	 * 
	 * @param directoryName
	 * @param wildcardFilter
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Collection getListOfFiles(String directoryName, String wildcardFilter)
	  {
	    File directory = new File(directoryName);
	    return FileUtils.listFiles(directory, 
	        new WildcardFileFilter(wildcardFilter), null);
	  }
}